<?php

class DependenceComponent extends object {
	var $opml_results = array();
	
	function getRootFeedfolder($user_id) {
		$folder = new Feedfolder();
		$root_folder = $folder->find('first', array('conditions' => array('user_id'=>$user_id,'root'=>'1')));
		$root_id = -1;
		if (isset($root_folder['Feedfolder'])) {
			$root_id = $root_folder['Feedfolder']['id'];
		} else {
			$root_data = array(
				'Feedfolder' => array(
					'label' => '[root]',
					'user_id' => $user_id,
					'root' => 1
				)
			);
				
			$folder->create();
			$folder->save($root_data);
			
			$root_id = $folder->id;
		}
		
		
		return $root_id;
	} // getRootFeedfolder()
	
	function processOPML($data, $user_id) {
		$opml = simplexml_load_string($data);
		$this->opml_results = array('folders' => 0, 'feeds' => 0);
		
		if (isset($opml->body)) {
			$body = $opml->body;
			$rd = '';
			
			$root_id = $this->getRootFeedfolder($user_id);
			
			
			foreach ($body->outline as $otln) {
				$this->_processOutline($otln, $root_id, $user_id);
			}
			
			//return $rd;
		} else {
			return false;
		}
		
		return array('folders' => $this->opml_results['folders'], 'feeds' => $this->opml_results['feeds']);
	} // processOPML()
	
	function _processOutline($otln, $folder_id, $user_id) {
		$attr = $otln->attributes();
		
		if (isset($attr->type) && isset($attr->htmlUrl) && isset($attr->xmlUrl)) {
			
			$feed = new Feed();
			
			$data = array(
				'Feed' => array(
				  'title' => $attr->title,
					'text' => $attr->text,
					'html' => $attr->htmlUrl,
					'xml' => $attr->xmlUrl,
					'feedfolder_id' => $folder_id
				)
			);
			
			$feed->create();
			$feed->save($data);
			$this->opml_results['feeds']++;
			
		} else {
			$folder = new Feedfolder();
			
			$data = array(
				'Feedfolder' => array(
					'label' => $attr->title,
					'user_id' => $user_id
				)
			);
			
			
			
			$folder->create();
			$folder->save($data);
			$this->opml_results['folders']++;
			
			//$ret_val = '[' . $attr->title . "]\n";
			
			foreach ($otln->outline as $sub_otln) {
				//$ret_val .= '  ' . $this->_processOutline($sub_otln, $folder->id, $user_id) . "\n";
				$this->_processOutline($sub_otln, $folder->id, $user_id);
	  	}
			//return $otln
			//return $ret_val;
		}
		
		//return (isset($attr->type) ? '[' . $attr->type . '] ' : '[folder] ') . $attr->text . ' : ' . $attr->title;
	} // _processOutline()
} // class DepLib

?>
